<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>

<title>Plupload - Custom example</title>

<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/plupload/3.1.2/plupload.full.min.js"></script>
<!--<script type="text/javascript" src="../js/plupload.full.min.js"></script>-->

<style type="text/css">
	*{
		margin: 0;padding: 0;box-sizing: border-box;
	}
	#original{
		height: 100px;
	}
	#original img{
		height: 100px;
	}
	.wrap{
		position: relative;
		height: 400px;
		background: white;
		padding: 30px 10px;
		min-width: 760px;
	}
	.wrap>div:nth-child(2){
		position: absolute;
		left: 75%;
		top: 30px;
		width: 24%;
		padding: 10px;
		overflow: hidden;
	}
	.wrap>div:nth-child(3){
		position: absolute;
		left: 0;
		top: 0;
		bottom: 0;
		width: 100%;
		padding: 10px;
		z-index: 1;
		background: white;
		display: none;
	}
	.wrap>div:nth-child(4){
		position: absolute;
		left: 0;
		top: 0;
		bottom: 0;
		width: 100%;
		padding: 10px;
		z-index: 2;
		background: white;
		display: none;
	}
	#result{
		width: 75%;
		min-width: 540px;
		height: 300px;
	    border: 1px solid #ddd;
	    display: block;
	    text-align: center;
	    border-radius: 1px;
	    background: #f5f5f5;
	    display: flex;
	    align-items: center;justify-content: center;
	}
	#result>div{
		/*background-color: white;*/
		background-position: center;
		background-size: cover;
		background-repeat: no-repeat;
	}
	.scale{
	    border: solid 1px #aaa;
	    width: 100px;
	    padding: 5px;
	    text-align: center;
	    margin-top: 1px;
	}
	.scale.selected{
		border: solid 1px green;
	}
</style>
</head>
<body style="font: 13px Verdana; background: #eee; color: #333">
<h1>Custom example</h1>
<br /><br />

<div id="container">
    <a id="pickfiles" href="javascript:;">[Select files]</a> 
    <a id="uploadfiles" href="javascript:;">[Upload files]</a>
</div>
<div id="original"></div>
<div class="wrap">
	<div id="result">
		<div></div>
	</div>
	<div>
		<input id="autocrop" type="checkbox" value="autocrop" name="autocrop" />
		<label for="autocrop" style="font-weight: bold;font-size: 14px;">Auto Crop Image</label>
		<br />
		<div style="padding:20px 0 0 20px;">
			<input id="byScale" type="radio" value="1" name="switchtype" checked="checked"/>
			<label for="byScale" style="font-weight: bold;font-size: 14px;">By Scale</label>
			<div class="scale selected" w="16" h="9" data-rate="true" style="margin-top: 10px;">16:9</div>
			<div class="scale" w="4" h="3" data-rate="true">4:3</div>
			<div class="scale" w="1" h="1" data-rate="true">1:1</div>
			<div class="scale" w="2" h="3" data-rate="true">2:3</div>
		</div>
		<div style="padding:10px 0 0 20px;">
			<input id="bySize" type="radio" value="2" name="switchtype" />
			<label for="bySize" style="font-weight: bold;font-size: 14px;">By Size</label>
			<div>Width(px)</div>
			<input class="bySizeWidth bySizeInput" type="number" value="480" style="width: 100px; text-align: center;height: 25px;line-height: 25px;" />
			<div>Height(px)</div>
			<input class="bySizeHeight bySizeInput" type="number" value="360" style="width: 100px; text-align: center;height: 25px;line-height: 25px;" />
			<div style="padding-top: 5px;">
				<select class="selectSize" style="height: 25px;">
				  <option value="-1">Select A Size</option>
				  <option value="500,200">500*200</option>
				  <option value="800,200">800*200</option>
				</select>
			</div>
			<div style="padding-top: 5px;">
				<input id="usedefault" type="checkbox" value="2s" name="usedefault" />
				<label for="usedefault" >Try Use Default</label>
			</div>
		</div>
	</div>
	<div class="div-video">
		<video style="width: 100%;height: 350px;" controls>
		</video>
	</div>
	<div class="div-audio">
		<audio style="width: 50%;height: 100px;" controls>
		</audio>
	</div>
</div>
<br />
<input type="button" name="submit" id="submit" value="submit" style="width: 100px;height: 30px;"/>
<div class="last"></div>
<script type="text/javascript">
var fileList={};
var options={
	rate:false,
	width:parseFloat($(this).attr("w")),
	height:parseFloat($(this).attr("h")),
};

$(".scale").on("click",function(){
	$(".scale").removeClass("selected");
	$(this).addClass("selected");
	displayImg();
});
$("[name='switchtype'],[name='autocrop']").on("change",function(){
	displayImg();
});
$(".bySizeInput").on("input",function(){
	displayImg();
});
$(".selectSize").on("change",function(){
	var v=$(this).val();
	if(v.toString()!="-1"){
		var arr = v.split(",");
		$(".bySizeWidth").val(arr[0]);
		$(".bySizeHeight").val(arr[1]);
		$(".selectSize").val("-1");
		displayImg();
	}
});

function displayImg(){
	var height = $("#result").height();
	if($("#autocrop:checked").length==0){
		$("#result>div").css({
			width:'100%',
			height:`${height}px`,
			backgroundSize:"contain",
		});
	}else{
		if($("[name='switchtype']:checked").val()=="1"){
			var obj=$(".scale.selected");
			options.rate=obj.data("rate");
			options.width=parseFloat(obj.attr("w"));
			options.height=parseFloat(obj.attr("h"));
		}else{
			options.rate=false;
			options.width=$(".bySizeWidth").val();
			options.height=$(".bySizeHeight").val();
		}
		
		var rate = options.width/options.height;
		var width= height * parseFloat(rate);
		$("#result>div").css({
			width:`${width}px`,
			height:`${height}px`,
			backgroundSize:"cover"
		});
	}
}

//点击图片预览
$(document).on("click","#original>*",function(){
	var filetype=$(this).attr("filetype");
	var fileid = $(this).attr("fileid");
	
	$(".div-video,.div-audio").hide();
	if(filetype!="image") $(".div-"+filetype).show();
	else{
		var fileObj=uploader.getFile(fileid);
		displayImg();
		$("#result>div").css("background-image",`url(${fileObj.imgsrc})`);
	}
});

//提交
$("#submit").on("click",function(){
	if(uploader.files.length<=0) return;
	if($("#autocrop:checked").length>0){
		for(var fileObj of uploader.files){
			cropImage(fileObj);
		}
	}
	//submit
	
});

//剪裁
function cropImage(fileObj){
	var img=new Image();
	img.src=fileObj.imgsrc;
	var targetWidth=0,targetHeight=0;
	var imgX=0,imgY=0;
	var rate=parseFloat(options.width)/parseFloat(options.height);
	if(parseFloat(img.width/img.height) >= rate ){
		targetHeight=img.height;
		targetWidth=targetHeight*rate;
		imgX=(img.width-targetWidth)/2;
	}else{
		targetWidth=img.width;
		targetHeight=targetWidth/rate;
		imgY=(img.height-targetHeight)/2;
	}
	
	var scale=1;
	if(!options.rate){
		scale=options.width/targetWidth;
	}
	
	$("body").append(`
		<canvas id="myCanvas" width="${options.rate?targetWidth:options.width}" height="${options.rate?targetHeight:options.height}" style="border:1px solid #d3d3d3;display:none;">
		Your browser does not support the HTML5 canvas tag.
		</canvas>
	`);
	var c=document.getElementById("myCanvas");
	var ctx=c.getContext("2d");
	ctx.scale(scale,scale);
	ctx.drawImage(img,imgX,imgY,targetWidth,targetHeight,0,0,targetWidth,targetHeight);
	fileObj.imgsrcCrop=c.toDataURL();
	$("#myCanvas").remove();
	$(".last").append(`<img src="${c.toDataURL()}"><br />`);
}


var uploader = new plupload.Uploader({
	runtimes : 'html5',
	browse_button : 'pickfiles', // you can pass an id...
	container: document.getElementById('container'), // ... or DOM Element itself
	url : 'upload.php',
	flash_swf_url : '../js/Moxie.swf',
	silverlight_xap_url : '../js/Moxie.xap',
//	filters : {
//		max_file_size : '10mb',
//		mime_types: [
//			{title : "Image files", extensions : "jpg,gif,png"},
//			{title : "Zip files", extensions : "zip"}
//		]
//	},
	init: {
		FilesAdded: function(up, files) {
			plupload.each(files, function(file) {
		        if (file.type == 'image/gif') {
//		            var fr = new moxie.file.FileReader();
//		            fr.onload = function () {
//		                file.imgsrc = fr.result;
//		                fr.destroy();
//		                fr = null;
//		                $("#original").html()
//		                $("#original").append(`<img fileid="${file.id}" src="${file.imgsrc}" />`);
////		                $("#original").append(`<div fileid="${file.id}">${file}</div>`);
//		            }
//		            fr.readAsDataURL(file.getSource());
		        } else if(/image\//.test(file.type)) {
		            var preloader = new moxie.image.Image();
		            preloader.onload = function() {
		                var imgsrc = preloader.type == 'image/jpeg' ? preloader.getAsDataURL('image/jpeg', 100) : preloader.getAsDataURL(); //得到图片src,实质为一个base64编码的数据
		                file.imgsrc = imgsrc;
		                file.width=preloader.width;
		                file.height=preloader.height;
		                preloader.destroy();
		                preloader = null;
		                $("#original").html()
		                $("#original").append(`<div filetype="image" fileid="${file.id}">${file.name}</div>`);
		            };
		            preloader.load(file.getSource());
		        }else if(/video\//.test(file.type)){
		        	var fr = new moxie.file.FileReader();
		            fr.onload = function () {
		                $("video").attr("src",`${fr.result}`);
		                fr.destroy();
		                fr = null;
		                $("#original").append(`<div filetype="video" fileid="${file.id}">${file.name}</div>`);
		            }
		            fr.readAsDataURL(file.getSource());
		        }else if(/audio\//.test(file.type)){
		        	var fr = new moxie.file.FileReader();
		            fr.onload = function () {
		                $("audio").attr("src",`${fr.result}`);
		                fr.destroy();
		                fr = null;
		                $("#original").append(`<div filetype="audio" fileid="${file.id}">${file.name}</div>`);
		            }
		            fr.readAsDataURL(file.getSource());
		        }
			});
			
			setTimeout(function(){
				$("#original>div").last().trigger("click");
			},300);
		},
		Error: function(up, err) {
			document.getElementById('console').appendChild(document.createTextNode("\nError #" + err.code + ": " + err.message));
		}
	}
});

uploader.init();

</script>
</body>
</html>
